<?php
/**
 * +--------------------------------------------------------+
 * @Created by Phpstorm.
 * @Category NginxsController.php
 * @Depiction
 * @Author hwy <429208948@qq.com>
 * @Date 2022/3/16  10:15
 * +--------------------------------------------------------+
 */

namespace App\Http\Controllers\Admin\V1;


use App\Util\NginxLog;
use Illuminate\Http\Request;

class NginxsController extends Controller
{
    public function index(Request $request)
    {
        try {
            $rules      = [
                'offset'     => ['required', 'numeric', 'gte:0'],
                'limit'      => ['required', 'numeric', 'gte:1', 'lte:100'],
                'start_at'   => ['required_with:end_at', 'date_format:Y-m-d H:i:s', 'before_or_equal:end_at'],
                'end_at'     => ['required_with:start_at', 'date_format:Y-m-d H:i:s', 'after_or_equal:start_at'],
                'file'       => ['required', 'string',],
                'ip'         => ['nullable', 'string',],
                'method'     => ['nullable', 'string',],
                'uri'        => ['nullable', 'string',],
                'http_code'  => ['nullable', 'string',],
                'is_warning' => ['nullable', 'boolean',],
                'is_error'   => ['nullable', 'boolean',],
                'is_robot'   => ['nullable', 'boolean',],
                'is_mobile'  => ['nullable', 'boolean',],
            ];
            $attributes = [
                'offset' => '起始数',
                'limit'  => '每页条数',
            ];
            $messages   = [];
            $validate   = $this->validate($request, $rules, $messages, $attributes);

            $nginxLog = new NginxLog($validate['file']);

            $logs = $nginxLog->get();

            //where
            $logs = $nginxLog->getByWhere($logs, $validate);

            $total = $logs->count();

            $offset = $request->input('offset', 0);
            $length = $request->input('limit', 10);
            $offset = ($offset - 1 < 0 ? 0 : $offset - 1) * $length;

            $data = $logs->slice($offset, $length);

            $res_data = [
                'data'  => array_values($data->toArray()),
                // 'data'  => $data->toArray(),
                'total' => $total,
            ];

            return $this->responseSuccessData('请求成功！', $res_data);


        } catch (\Exception $e) {

            return $this->responseErrorData($e->getMessage());
        }

    }

}
